import AuthStorage from "@/utils/AuthStorage";
import Util from "@/utils/Util"
import Request from "@/utils/Request";
import qs from 'qs';
import { get } from "@/utils/RequestUtil";
import { Session } from "@/utils/StorageData";

export function setTokenInfo(commit, data) {
	const { accessToken, accessExpires, refreshToken, refreshExpires } = data
	// 存储 token 到浏览器缓存
	AuthStorage.setAccessToken(accessToken, accessExpires)
	commit('SET_ACCESS_TOKEN', accessToken)
	// 存储刷新令牌到缓存
	AuthStorage.setRefreshToken(refreshToken, refreshExpires)
	commit('SET_REFRESH_TOKEN', refreshToken)
}

const userInfosModule = {
	namespaced: true,
	state: {
		userInfo: {},
		accessToken: AuthStorage.getAccessToken(),
		refreshToken: AuthStorage.getRefreshToken()
	},
	mutations: {
		// 设置用户信息
		SET_USER(state, data) {
			state.userInfo = data;
		},
		SET_ACCESS_TOKEN(state, data){
			state.accessToken = data
		},
		SET_REFRESH_TOKEN(state, data){
			state.refreshToken = data
		}
	},
	actions: {
		login({ commit }, data) {
			return new Promise(resolve => {
				const { userName, password, captcha, key } = data
				const body = { username: userName, password, grant_type: 'password', deviceName: window.navigator.userAgent, captcha, key }
				const authorization = Util.base64Encode(`${process.env.VUE_APP_CLIENT_ID}:${process.env.VUE_APP_CLIENT_SECRET}`)
				Request({
					url: '/oauth/token',
					method: 'post',
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'Authorization': `Basic ${authorization}`
					},
					data: qs.stringify(body),
				}).then(res => {
					if (res.code === 200) {
						setTokenInfo(commit, res.data)
					}
					// 设置授权令牌和刷新令牌
					resolve(res)
				}).catch((res) => {
					resolve(res || { code: 500, msg: '登录失败'})
				})
			})
		},
		/**
		 * 令牌刷新
		 * @param commit
		 * @returns {Promise<unknown>}
		 */
		async refresh_token({ commit }) {
			return new Promise(resolve => {
				const token = AuthStorage.getAccessToken()
				if (token) {
					resolve({ code: 200 })
				} else {
					const refresh = AuthStorage.getRefreshToken()
					if (refresh) {
						const body = { grant_type: 'refresh_token', refresh_token: refresh, deviceName: window.navigator.userAgent }
						const authorization = Util.base64Encode(`${process.env.VUE_APP_CLIENT_ID}:${process.env.VUE_APP_CLIENT_SECRET}`)
						Request({
							url: 'oauth/token',
							method: 'post',
							headers: {
								'Content-Type': 'application/x-www-form-urlencoded',
								'Authorization': `Basic ${authorization}`
							},
							data: qs.stringify(body),
						}).then(res => {
							if (!res || res.code !== 200) {
								resolve({code:401})
							} else {
								setTokenInfo(commit, res.data)
								resolve(res)
							}
						})
					} else {
						resolve({ code: 401 })
					}
				}
			})
		},
		getUserInfo({ commit } ) {
			return new Promise(resolve => {
				get('/user/current')
					.then(res => {
						if (res.code === 200) {
							commit('SET_USER', res.data)
							AuthStorage.setUserInfo(res.data)
						}
						resolve(res)
					})
			})
		},
		getSysMenu() {
			return new Promise(resolve => {
				get('/menuAuth/clientMenu/' + process.env.VUE_APP_CLIENT_ID)
					.then(res => {
						resolve(res)
					})
			})
		}
	},
};

export default userInfosModule;
